//
//  AppDelegate.m
//  ZKCompetitionApp
//
//  Created by 凯朱 on 2019/8/20.
//

#import "AppDelegate.h"
#import <UserNotifications/UserNotifications.h>
@interface AppDelegate (){
    UIBackgroundTaskIdentifier backgroundTask; //用来保存后台运行任务的标示符
    NSTimer *_timer;
    NSInteger _time;
}

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   
    //初始化window
    [self initWindow];

    //开启防崩溃框架
    [self openAvoidCrash];
    [[UserManager sharedUserManager] getUserInfo];
    //键盘弹出监听
    [self registerIQKeyboardManager];
    
    //初始化app服务
    [self initService];
    
    //初始化用户系统
    [self initUserManager];
    
    return YES;
}

- (void)startBackgroundTask{
    
    UIApplication *application = [UIApplication sharedApplication];
    //通知系统, 我们需要后台继续执行一些逻辑
    backgroundTask = [application beginBackgroundTaskWithExpirationHandler:^{
        //超过系统规定的后台运行时间, 则暂停后台逻辑
        [application endBackgroundTask:self->backgroundTask];
        self->backgroundTask = UIBackgroundTaskInvalid;
        [self destoryTimer];
        NSLog(@"后台任务停止");
        [self startBackgroundTask];
    }];
    
    //判断如果申请失败了, 返回
    if (backgroundTask == UIBackgroundTaskInvalid) {
        NSLog(@"beginground error");
        return;
    }
    //已经成功向系统争取了一些后台运行时间, 实现一些逻辑, 如网络处理
    //some code
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (!self->_timer) {
            self->_timer = [NSTimer timerWithTimeInterval:1.0
                                                     target:self
                                                   selector:@selector(timerHandle)
                                                   userInfo:nil
                                                    repeats:YES];
            
            [[NSRunLoop currentRunLoop] addTimer:self->_timer forMode:NSRunLoopCommonModes];
            [[NSRunLoop currentRunLoop]run];
        }
    });
    
}


-(void)destoryTimer{
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

-(void)timerHandle{
    _time ++;
    NSLog(@"后台任务 - %ld",_time);
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
//    [self startBackgroundTask];
    
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"backToApp" object:nil userInfo:nil];
    //通知系统, 我们需要后台继续执行一些逻辑
//    [application endBackgroundTask:self->backgroundTask];
//    self->backgroundTask = UIBackgroundTaskInvalid;
//    [self destoryTimer];
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    NSLog(@"应用被杀死");
//    [[NSUserDefaults standardUserDefaults] setObject:@"N" forKey:@"isLogined"];
//    [[NSUserDefaults standardUserDefaults] synchronize];
//    [ZKHttpManager getHomepageEventWithParams:@{} finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
//
//    }];
}

@end
